const {Low} = require('lowdb')
const {JSONFile} = require('lowdb/node')
const path = require('path')
const {app} = require('@electron/remote')
const log = require('electron-log')

const configPath = path.join(app.getPath('userData'), 'low_config.json')
console.log('配置文件地址', configPath)
const adapter = new JSONFile(configPath)

// 初始化默认数据
const defaultUser = {
    opid: 'admin',
    password: 'admin1234',
    role: 'admin',
    name: '系统管理员'
}

const db = new Low(adapter, {
    user: {
        list: [defaultUser]
    }
})

export const getConfig = async (key) => {
    await db.read()
    let value = db.data
    if (!key) {
        return value
    }
    const keys = key.split('.')
    for (const k of keys) {
        value = value[k]
        if (value === undefined) return null
    }
    return value
}

export const setConfig = async (key, value) => {
    log.info(`setConfig: key='${key}', value=${JSON.stringify(value)}`)
    await db.read()
    const keys = key.split('.')
    let current = db.data
    for (let i = 0; i < keys.length - 1; i++) {
        current = current[keys[i]] ||= {}
    }
    current[keys[keys.length - 1]] = value
    await db.write()
}

export const initDefaultUser = async () => {
    log.info('initDefaultUser')
    await setConfig('user.list', [defaultUser])
}

export const updateConfig = async (key, updater) => {
    log.info(`updateConfig: key='${key}'`)
    await db.read()
    const value = await getConfig(key)
    const updated = updater(value)
    await setConfig(key, updated)
}
